package com.code;

import org.junit.Test;

public class Prime {


    @Test
    public void test() {
        System.out.println(isPrime(65537));
        System.out.println(factorizationPrime(3337));
    }

    /**
     * 判断质数
     * 1、假设a*b=x 就有min(a,b)<=sqrt(x) 试除到min(a,b)即可
     * 2、可以简单的排除2的倍数
     *
     * @return 是否是质数
     */
    public static boolean isPrime(int x) {
        if (x < 2) {
            return false;
        }
        if (x % 2 == 0) {
            return false;
        }
        int s = (int) Math.sqrt(x);
        for (int i = 3; i <= s; i += 2) {
            if (x % i == 0) {
                return false;
            }
        }
        return true;
    }

    /**
     * 因数分解
     */
    public static int factorizationPrime(int x) {
        if (x < 2) {
            return 1;
        }
        if (x % 2 == 0) {
            return 2;
        }
        int s = (int) Math.sqrt(x);
        for (int i = 3; i <= s; i += 2) {
            if (x % i == 0) {
                return i;
            }
        }
        return 0;
    }
}
